﻿/****************************************************************
  Author:  Ievgenii Nazaruk, ievgenii.nazaruk@gmail.com 
 License:  Microsoft Public License (Ms-PL)
          ( http://www.opensource.org/licenses/ms-pl.html or
            http://www.microsoft.com/opensource/licenses.mspx )
*****************************************************************/

using System;
using WebLayer;
using System.Collections.Generic;
using HtmlAgilityPack;


namespace WebPageParser
{
    class CourseTableEntry
    {
        public String RowNumber = null;
        public String Course    = null;
        public String Level     = null;
        public String Status    = null;
    }    

    class CourseWebPage: SiteWebPage
    {
        private CourseTableEntry m_tableHeader = null;
        public CourseTableEntry TableHeader
        {
            get
            {
                if (m_tableHeader == null)
                {
                    Request();
                }
                return m_tableHeader;
            }
        }

        private List<CourseTableEntry> m_tableContent = null;
        public  List<CourseTableEntry> TableContent
        {
            get
            {
                if (m_tableContent == null)
                {
                    Request();
                }
                return m_tableContent;
            }
        }


        public CourseWebPage():
        base("Course", GetActionPageUri("course"))
        {
            
        }

        public override void Request()
        {
            m_tableHeader  = new CourseTableEntry();
            m_tableContent = new List<CourseTableEntry>();

            base.Request();
        }

        protected override void OnResponse(System.Net.HttpWebRequest request, System.Net.HttpWebResponse response)
        {
            base.OnResponse(request, response);

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(PageContent);

            //Course html page has only one table. Select it;
            HtmlNode node = doc.DocumentNode.SelectSingleNode("//table");

            if (node != null)
            { 
                /* 4 columns in a table */
                HtmlTableParser tableParser = new HtmlTableParser(4, node);
                tableParser.TransformTable<CourseTableEntry>(TableContent, Transformer);
                m_tableHeader = Transformer(tableParser.Header, tableParser.HtmlHeader);
            }
        }

        protected CourseTableEntry Transformer(HtmlTableRow textRow, HtmlTableRow htmlRow)
        {
            CourseTableEntry entry = new CourseTableEntry();

            entry.RowNumber = textRow[0];
            entry.Course = textRow[1];
            entry.Level = textRow[2];
            entry.Status = textRow[3];
            return entry;
        }
    }
}
